<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
require_once(BASEPATH.'../fuman/ebay/keys.php');
require_once(BASEPATH.'../fuman/ebay/eBaySession.php');

/*******************
***  ebay订单同步处理
***  
*** 2017/06/3
**********/
class Ebaydata
{
	
	function __construct()
	{    
		 $this->CI =& get_instance();
        $this->db1 = $this->CI->load->database('default', TRUE);
       $this->CI->load->library('Amazondata');
	}
	
	//Ebay第三方授权
	public function getuserToken($id)
	{
		$row = $this->db1->get_one("SELECT * from d_shop where id='".$id."'");
		$data=json_decode($row['amazonkey'],true);
		$devID=$data['ebaydevid'];
		$userToken=$data['ebayusertoken'];
		$appID=$data['ebayappid'];
		$certID=$data['ebaycertid'];
		$siteID=$data['ebaysiteid'];
		$RuName=$data['RuName'];
		$compatabilityLevel=$data['ebaycompatabilitylevel'];

		//沙盒
		//$appID='leoliu-TestApp-SBX-78e3a12c2-0e674ca7';
		//$certID='SBX-8e06383ec2be-13a8-4245-af8a-2433';
		//$devID='b7c7a78a-3373-4bc0-b036-0b318564d857';
		$RuName =$RuName?$RuName:'leo_liu-leoliu-TestApp--szqxm';

		$serverUrl='https://api.ebay.com/ws/api.dll';
		$verb = 'GetSessionID';
		$requestXmlBody = '<?xml version="1.0" encoding="utf-8"?>';
		$requestXmlBody .= '<GetSessionIDRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
		$requestXmlBody .= '<RuName>'.$RuName.'</RuName>';
		$requestXmlBody .= '</GetSessionIDRequest>';
		$session = new eBaySession($userToken, $devID, $appID, $certID, $serverUrl, $compatabilityLevel, $siteID, $verb);
		$responseXml = $session->sendHttpRequest($requestXmlBody);
		$xml=simplexml_load_string($responseXml);
		$SessionID = $xml->SessionID;
		if($SessionID)
		{
			//$url = "https://signin.sandbox.ebay.com/ws/eBayISAPI.dll?SignIn&RuName={$RuName}&SessID=".$SessionID;
			return array("SessionID"=>$SessionID,"RuName"=>$RuName);
		}else{
			return false;
		}
	}
	
	public function getuserTokensecond($id)
	{
		$row = $this->db1->get_one("SELECT * from d_shop where id='".$id."'");
		$data=json_decode($row['amazonkey'],true);
		$devID=$data['ebaydevid'];
		$userToken=$data['ebayusertoken'];
		$appID=$data['ebayappid'];
		$certID=$data['ebaycertid'];
		$siteID=$data['ebaysiteid'];
		$compatabilityLevel=$data['ebaycompatabilitylevel'];
		$RuName = $data['RuName']?$data['RuName']:$data['runame'];
		$SessionIDst = $data['SessionID'][0];
	
		//沙盒
		//$appID='leoliu-TestApp-SBX-78e3a12c2-0e674ca7';
		//$certID='SBX-8e06383ec2be-13a8-4245-af8a-2433';
		//$devID='b7c7a78a-3373-4bc0-b036-0b318564d857';

		//获取UserToken
		$newxml = '<?xml version="1.0" encoding="utf-8"?>';
		$newxml.= '<FetchTokenRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
		$newxml.= "<SessionID>$SessionIDst</SessionID>";
		$newxml.= '</FetchTokenRequest>';
		
		
		$serverUrl='https://api.ebay.com/ws/api.dll';
		$verb = 'FetchToken';
		$session = new eBaySession($userToken, $devID, $appID, $certID, $serverUrl, $compatabilityLevel, $siteID, $verb);
		$responseXml = $session->sendHttpRequest($newxml);
		$xmlst=simplexml_load_string($responseXml);
		$data = json_decode(json_encode($xmlst),TRUE);
		if($data['Ack'] =='Success')
		{
			return $data['eBayAuthToken'];
		}else{
			return false;
		}
	}
		
	

//获取ebaytoken信息
  public function getebaytoken($id){
 ini_set('max_execution_time', '0');
   $row = $this->db1->get_where("d_shop","id={$id}")->result_array();


  foreach ($row as $v) {
    $shopid=$v['id'];
  	$name=$v['name'];
    $data=json_decode($v['amazonkey'],true);
    $devID=$data['ebaydevid'];
    $userToken=$data['ebayusertoken'];
    $appID=$data['ebayappid'];
    $certID=$data['ebaycertid'];
    $siteID=$data['ebaysiteid'];
    $compatabilityLevel=$data['ebaycompatabilitylevel'];
    //return BASEPATH.'../fuman/ebay/keys.php';
    //return $shopid.','.$name.','.$devID.','.$userToken.','.$appID.','.$certID.','.$siteID.','.$compatabilityLevel;

  }

	
		//$this->GetAPIAccessRules($shopid,$name,$devID,$userToken,$appID,$certID,$siteID,$compatabilityLevel);
	$this->GetAccount($shopid,$name,$devID,$userToken,$appID,$certID,$siteID,$compatabilityLevel);

  $this->GetOrders($shopid,$name,$devID,$userToken,$appID,$certID,$siteID,$compatabilityLevel);
 //return $data;
}

//获取BuyItNowFee
public function GetAccount($shopid,$name,$devID,$userToken,$appID,$certID,$siteID,$compatabilityLevel)
{
	$serverUrl='https://api.ebay.com/ws/api.dll';
	$verb = 'GetAccount';
	$requestXmlBody = '<?xml version="1.0" encoding="utf-8"?>';
	$requestXmlBody .= '<GetAccountRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
	$requestXmlBody .= '<RequesterCredentials>';
	$requestXmlBody .= " <eBayAuthToken>$userToken</eBayAuthToken>";
	$requestXmlBody.="<AccountEntrySortType>AccountEntryFeeTypeAscending</AccountEntrySortType>";
	$requestXmlBody.="<AccountHistorySelection>LastInvoice</AccountHistorySelection>";
	$requestXmlBody .= '</RequesterCredentials>';
	$requestXmlBody .= "</GetAccountRequest>";
	$session = new eBaySession($userToken, $devID, $appID, $certID, $serverUrl, $compatabilityLevel, $siteID, $verb);
	$responseXml = $session->sendHttpRequest($requestXmlBody);
	$xml=simplexml_load_string($responseXml);
	$data = json_decode(json_encode($xml),TRUE);
	if($data['Ack'] =='Success'){
		$InvoiceDate = $data['AccountSummary']['InvoiceDate'];
		$InvoiceBalance = $data['AccountSummary']['InvoiceBalance'];
		$InvoiceDate = date("Y-m-d",strtotime($InvoiceDate));
		$row = $this->db1->get_where("db_ebay_bill","shopId='".$shopid."' AND endDate = '".$InvoiceDate."'")->result_array();
		if($row)
		{
			$exchange=$this->db1->get_where("d_moneyrate","name='USD'")->result_array();
			$exchangerate=$exchange[0]["rate"];
			$insertionFeeRMB =  $exchangerate * $InvoiceBalance;
			$this->db1->update("db_ebay_bill",array('insertionFee'=>$InvoiceBalance,"endDate"=>$InvoiceDate,"insertionFeeRMB"=>$insertionFeeRMB)," id='".$row[0]['id']."'");
		}else{
			$post="";
			$post['shopId'] = $shopid;
			$post['shopName'] = $name;
			$exchange=$this->db1->get_where("d_moneyrate","name='USD'")->result_array();
			$exchangerate=$exchange[0]["rate"];
			$post['moneyRate'] =$exchangerate ;
			$post['moneyType'] ='USD' ;
			$post['insertionFee'] = $InvoiceBalance;
			$post['insertionFeeRMB'] = $exchangerate * $InvoiceBalance;
			//$post['startDate'] = $shopid;
			$post['endDate'] = $InvoiceDate;
			$post['createId'] = 0;
			$post['createName'] = 'SYSTEM';
			$post['addTime'] = date("Y-m-d H:i:s");
			$this->db1->insert('db_ebay_bill',$post);
		}
	}
	/*
	if(count($data["AccountEntries"]['AccountEntry']))
	{
		//$price=$yunprice=$otherprice=0;
		foreach($data["AccountEntries"]['AccountEntry'] as $key=>$rs)
		{
			$Description[] = $rs["Description"];
			if($rs['Description'] == '物品刊登費')
			{
				$price[] =$rs["GrossDetailAmount"];//物品刊登費
			}
			if($rs['Description'] == '成交費' || $rs['Description'] =='包括運費的成交費')
			{
				$yunprice[] = $rs["GrossDetailAmount"];//物品刊登費
			}
			if($rs['Description'] == '特大圖片瀏覽費用' || $rs['Description'] =='廣告費')
			{
				$otherprice[] = $rs["GrossDetailAmount"];//物品刊登費
			}
		}
	}
	*/
	
}

//获取call
public function GetAPIAccessRules($shopid,$name,$devID,$userToken,$appID,$certID,$siteID,$compatabilityLevel)
{                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
	$serverUrl='https://api.ebay.com/ws/api.dll';
	$verb = 'GetApiAccessRules';
	$requestXmlBody = '<?xml version="1.0" encoding="utf-8"?>';
	$requestXmlBody .= '<GetApiAccessRulesRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
	$requestXmlBody .= '<RequesterCredentials>';
	$requestXmlBody .= " <eBayAuthToken>$userToken</eBayAuthToken>";
	$requestXmlBody .= '</RequesterCredentials>';
	$requestXmlBody .= "</GetApiAccessRulesRequest>";
	$session = new eBaySession($userToken, $devID, $appID, $certID, $serverUrl, $compatabilityLevel, $siteID, $verb);
	$responseXml = $session->sendHttpRequest($requestXmlBody);

	print_r($responseXml);
	die;
}

//获取订单
public function GetOrders($shopid,$name,$devID,$userToken,$appID,$certID,$siteID,$compatabilityLevel,$page=1){

$serverUrl='https://api.ebay.com/ws/api.dll';
$verb = 'GetOrders';


	/*
	$CreateTimeFrom = gmdate("Y-m-d\TH:i:s",time()-3600*24*5);
	$CreateTimeTo = gmdate("Y-m-d\TH:i:s");
	$requestXmlBody = '<?xml version="1.0" encoding="utf-8" ?>';
	$requestXmlBody .= '<GetOrdersRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
	$requestXmlBody .= '<DetailLevel>ReturnAll</DetailLevel>';
	$requestXmlBody .= "<CreateTimeFrom>$CreateTimeFrom</CreateTimeFrom><CreateTimeTo>$CreateTimeTo</CreateTimeTo><SortingOrder>Ascending</SortingOrder>";
	$requestXmlBody .= "<RequesterCredentials><eBayAuthToken>$userToken</eBayAuthToken></RequesterCredentials>";
	$requestXmlBody .= '</GetOrdersRequest>';
	$session = new eBaySession($userToken, $devID, $appID, $certID, $serverUrl, $compatabilityLevel, $siteID, $verb);
	$responseXml = $session->sendHttpRequest($requestXmlBody);
   */
	
	
	$requestXmlBody = '<?xml version="1.0" encoding="utf-8" ?>';
	$requestXmlBody .= '<GetOrdersRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
	$requestXmlBody .= '<DetailLevel>ReturnAll</DetailLevel>';
	$requestXmlBody .= '<NumberOfDays>1</NumberOfDays>';
	$requestXmlBody .= "<Pagination><PageNumber>$page</PageNumber></Pagination>";
	$requestXmlBody .= '<OrderRole>Seller</OrderRole><SortingOrder>Ascending</SortingOrder>';
	$requestXmlBody .= "<RequesterCredentials><eBayAuthToken>$userToken</eBayAuthToken></RequesterCredentials>";
	$requestXmlBody .= '</GetOrdersRequest>';
	$session = new eBaySession($userToken, $devID, $appID, $certID, $serverUrl, $compatabilityLevel, $siteID, $verb);
	$responseXml = $session->sendHttpRequest($requestXmlBody);
	

if (stristr($responseXml, 'HTTP 404') || $responseXml == '')
    die('<P>Error sending request');
$xml=simplexml_load_string($responseXml);

$responseDoc = new DomDocument();
$responseDoc->loadXML($responseXml);
$xmlname='uploads/eBay/'.date('Ymd').'/'.$name.time().'.xml';
$time=date('Ymd');
if(!file_exists("uploads/eBay")){
		//如果不存在文件夹，则创建文件夹
		mkdir("uploads/eBay");		
}
if (!file_exists("uploads/eBay/{$time}")) {
	mkdir("uploads/eBay/{$time}");
}
$responseDoc->save($xmlname);
$ack=$responseDoc->getElementsByTagName('Ack')->item(0)->nodeValue;
if ($ack=='Failure') exit;
$currencyID=array();
$xmllen=$responseDoc->getElementsByTagName('OrderArray')->item(0)->childNodes->length;
for ($i=0; $i <$xmllen ; $i++) { 
$tagname=$responseDoc->getElementsByTagName('AdjustmentAmount');
 $node  = $tagname->item($i);
$currencyID[]=$node->getAttribute('currencyID');
}
// var_dump($xml);
// $tagname=$responseDoc->getElementsByTagName('AdjustmentAmount');
//  $node  = $tagname->item(0);
// $currencyID=$node->getAttribute('currencyID');
// $responseDoc->save('eaby.xml');
$data = json_decode(json_encode($xml),TRUE);

//if($_COOKIE["userid"]==295){
//	print_r($data);
//	//die;
//}
//$data=json_decode(json_encode($xml),true);
//return $data;
if(!isset($data['OrderArray']['Order'])) return 0;
$order=$data['OrderArray']['Order'];

//删除30天之前的订单
$deletetime = time()-30*24*3600;
$deletesql="delete from db_ebayorder where e_updata_time<'{$deletetime}';";
 $this->db1->query($deletesql);

//设置允许导入列
 $legalcolumn=array('OrderID','OrderStatus','AdjustmentAmount','AmountPaid','AmountSaved','CheckoutStatus','ShippingDetails','CreatedTime','PaymentMethods','SellerEmail','ShippingAddress','ShippingServiceSelected','Subtotal','Total','ExternalTransaction','TransactionArray','BuyerUserID','PaidTime','ShippedTime','IntegratedMerchantCreditCardEnabled','PickupDetails','PickupMethodSelected','LogisticsPlanType','EIASToken','PaymentHoldStatus','IsMultiLegShipping','MonetaryDetails','SellerUserID','SellerEIASToken','CancelStatus','ExtendedOrderID','ContainseBayPlusTransaction','BuyerCheckoutMessage','CreatingUserRole','PaymentHoldDetails','BundlePurchase');

$into=array();
$leng=count($currencyID);
for ($i=0; $i < $leng ; $i++) { 
unset($into);
$into['e_updata_time']=time();
$into['is_updata']=0;
$into['shopid']=$shopid;
if (empty($currencyID[$i])) {
	continue;
}
$into['currencyID']=$currencyID[$i];


$into['BuyerCheckoutMessage']='';
$into['CreatingUserRole']='';
$into['PaymentHoldDetails']='';
if (!isset($order[0])) {
	
	foreach ($order as $key => $value) {
		if (!in_array($key, $legalcolumn)) continue;
	if ( is_array( $value )) {
		$value=json_encode($value);
	}
	$into[$key]=$value;
}

unset($sql);
			$sql="select count(*) as cou from db_ebayorder where OrderID='{$into['OrderID']}';";

			$orders= $this->db1->query($sql)->result_array();
            if ($orders[0]['cou']>=1) {
            	break;
            }
$this->db1->insert("db_ebayorder",$into);
break;
}

//  print_r($order[$i]);
// continue;
// $oneorder=$order[$i];
	foreach ($order[$i] as $key => $value) {
if (!in_array($key, $legalcolumn)) continue;
	if ( is_array( $value )) {
		$value=json_encode($value);
	}
	$into[$key]=$value;

}

            unset($sql);
			$sql="select count(*) as cou from db_ebayorder where OrderID='{$into['OrderID']}';";
			$orders= $this->db1->query($sql)->result_array();
            if ($orders[0]['cou']>=1) {
            	continue;
            }


// return json_encode($into);
$this->db1->insert("db_ebayorder",$into);
}
//判断页码，于当前页数
//这个是总的页数
$pagenum=$data['PaginationResult']['TotalNumberOfPages'];
if($pagenum>$page){
	$page++;
	$this->GetOrders($shopid,$name,$devID,$userToken,$appID,$certID,$siteID,$compatabilityLevel,$page);
}
//return json_encode($into);

}

// $devID="34177b3a-e131-4f11-a722-6054548b7e64";
// $userToken="AgAAAA**AQAAAA**aAAAAA**JdYjWQ**nY+sHZ2PrBmdj6wVnY+sEZ2PrA2dj6AAkouoDpaBpQqdj6x9nY+seQ**3MADAA**AAMAAA**4mhgMgjmdgRr4s2igqrrTQ8gP3vgylU9moOCINfKJDMjwaQvITDWwXMQ7yxCODZhuk7L+h+YvP777FBlDpfBjGynIdPgtL33hyH9bv73qjCRT3ULkX0BQISVv1ubFd4YUBx810ZwcmTJ/zxVZRkCP1QwttQ5iFbZBCkguwxBFOm/C4/Vedxi5zwFZuZ8lJVCOS8WsiRD5+AhE6F19BIMhuw5sYoKTjhWWfGqMhxaGZsEejPpZp2IIZmu4Ao/GM/6p8j1gEU6+3bIakiOPoav/ZiJ3IeXDK9xmOgZayEBvukF4bxWFgItQDe5ADYyQmO2QikQmdkw8rca2QthRM4AG4HyQT1GkNwURZzjWjHMpsjmq0Cmg8K3zh/h7c0K5dwg9+lp0ECQY9Yg52Oc2acezJZOZZCGYfWigJXK7+GNuRMOlq5qfjugyOpZQy8aVM71pIx0TMccjfly2oJD2wFrUVO4yYwyL2CzQow+fBGBqeagvYf+R55i1xP/642jdN6lbCjh8zMSmEcb8n1Ie4z9+O4Sx06JeaXpeqvsQaArkcJd3YuHGTGqaQWHKg+JjRSXTGGcHFtWdYaULumxcpwo8WAP8JKc7izceXGGPsaH7kaqltlD69dDbfom4SoZ95ymKJWQqowtY/8l3TYK9Yi0CcUURGY609etl6VkUcvWDYUkS6FquWEsYqMjPVoiTDGj0fNAGrxbj/OaxoWZSlQJDyEzeaU5FQQ6geb9kQt7EmCocQyMdedGlSeK8WJTF/hk";
// $appID="wangmx-testapp-SBX-0dbc19de5-274f9009";
// $certID="SBX-dbc19de5a5a1-1507-4646-81d5-55f0";
// $serverUrl='991';
// $siteID = 0;
// $serverUrl='https://api.ebay.com/ws/api.dll';
// //the call being made:
// $verb = 'GetOrders';
 // {"ebaydevid":"2222","ebayusertoken":"22222","ebayappid":"2222222","ebaycertid":"222222","ebaycompatabilitylevel":"2222222","ebaysiteid":"2222"}


 // create table IF NOT EXISTS db_ebayorder(
 //    	e_id INT(11) NOT NULL AUTO_INCREMENT,
 //    	is_updata text NOT NULL  COMMENT '是否同步到了正式表' ,
 //    	shopid text NOT NULL,
 //    	e_updata_time text NOT NULL,
 //    	currencyID text NOT NULL COMMENT '货币单位' ,
 //    	OrderID text NOT NULL,
 //    	OrderStatus text NOT NULL,
 //    	AdjustmentAmount text NOT NULL,
 //    	AmountPaid text NOT NULL,
 //    	AmountSaved text NOT NULL,
 //    	CheckoutStatus text NOT NULL,
 //    	ShippingDetails text NOT NULL,
 //    	CreatedTime text NOT NULL,
 //    	PaymentMethods text NOT NULL,
 //    	SellerEmail text NOT NULL,
 //    	ShippingAddress text NOT NULL,
 //    	ShippingServiceSelected text NOT NULL,
 //    	Subtotal text NOT NULL,
 //    	Total text NOT NULL,
 //    	ExternalTransaction text NOT NULL,
 //    	TransactionArray text NOT NULL,
 //    	BuyerUserID text NOT NULL,
 //    	PaidTime text NOT NULL,
 //    	ShippedTime text NOT NULL,
 //    	IntegratedMerchantCreditCardEnabled text NOT NULL,
 //    	EIASToken text NOT NULL,
 //    	PaymentHoldStatus text NOT NULL,
 //    	IsMultiLegShipping text NOT NULL,
 //    	MonetaryDetails text NOT NULL,
 //    	SellerUserID text NOT NULL,
 //    	SellerEIASToken text NOT NULL,
 //    	CancelStatus text NOT NULL,
 //    	ExtendedOrderID text NOT NULL,
 //    	ContainseBayPlusTransaction text NOT NULL,
 //    	BuyerCheckoutMessage text NOT NULL,
 //    	CreatingUserRole text NOT NULL,
 //    	PaymentHoldDetails text NOT NULL,
 //    	PRIMARY KEY ( e_id )
 //    	);
//  array(18) { ["OrderID"]=> string(26) "322418069097-1760760719011" ["OrderStatus"]=> string(6) "Active" ["AdjustmentAmount"]=> string(3) "0.0" ["AmountPaid"]=> string(5) "26.99" ["AmountSaved"]=> string(3) "0.0" ["CheckoutStatus"]=> array(5) { ["eBayPaymentStatus"]=> string(16) "NoPaymentFailure" ["LastModifiedTime"]=> string(24) "2017-06-03T00:39:22.000Z" ["PaymentMethod"]=> string(4) "None" ["Status"]=> string(10) "Incomplete" ["IntegratedMerchantCreditCardEnabled"]=> string(5) "false" } ["ShippingDetails"]=> array(5) { ["SalesTax"]=> array(4) { ["SalesTaxPercent"]=> string(3) "0.0" ["SalesTaxState"]=> array(0) { } ["ShippingIncludedInTax"]=> string(5) "false" ["SalesTaxAmount"]=> string(3) "0.0" } ["ShippingServiceOptions"]=> array(2) { [0]=> array(6) { ["ShippingService"]=> string(12) "ePacketChina" ["ShippingServiceCost"]=> string(3) "7.0" ["ShippingServicePriority"]=> string(1) "1" ["ExpeditedService"]=> string(5) "false" ["ShippingTimeMin"]=> string(1) "7" ["ShippingTimeMax"]=> string(2) "12" } [1]=> array(6) { ["ShippingService"]=> string(30) "ExpeditedShippingFromOutsideUS" ["ShippingServiceCost"]=> string(4) "22.0" ["ShippingServicePriority"]=> string(1) "2" ["ExpeditedService"]=> string(5) "false" ["ShippingTimeMin"]=> string(1) "1" ["ShippingTimeMax"]=> string(1) "4" } } ["InternationalShippingServiceOption"]=> array(2) { [0]=> array(4) { ["ShippingService"]=> string(18) "OtherInternational" ["ShippingServiceCost"]=> string(3) "7.0" ["ShippingServicePriority"]=> string(1) "1" ["ShipToLocation"]=> array(11) { [0]=> string(8) "Americas" [1]=> string(6) "Europe" [2]=> string(4) "Asia" [3]=> string(2) "CA" [4]=> string(2) "GB" [5]=> string(2) "CN" [6]=> string(2) "MX" [7]=> string(2) "DE" [8]=> string(2) "JP" [9]=> string(2) "FR" [10]=> string(2) "AU" } } [1]=> array(4) { ["ShippingService"]=> string(22) "ExpeditedInternational" ["ShippingServiceCost"]=> string(4) "22.0" ["ShippingServicePriority"]=> string(1) "2" ["ShipToLocation"]=> array(11) { [0]=> string(8) "Americas" [1]=> string(6) "Europe" [2]=> string(4) "Asia" [3]=> string(2) "CA" [4]=> string(2) "GB" [5]=> string(2) "CN" [6]=> string(2) "MX" [7]=> string(2) "DE" [8]=> string(2) "JP" [9]=> string(2) "FR" [10]=> string(2) "AU" } } } ["SellingManagerSalesRecordNumber"]=> string(3) "726" ["GetItFast"]=> string(5) "false" } ["CreatedTime"]=> string(24) "2017-06-03T00:39:21.000Z" ["PaymentMethods"]=> string(6) "PayPal" ["SellerEmail"]=> string(16) "cownsfia@126.com" ["ShippingAddress"]=> array(9) { ["Name"]=> array(0) { } ["Street1"]=> array(0) { } ["Street2"]=> array(0) { } ["CityName"]=> array(0) { } ["StateOrProvince"]=> array(0) { } ["CountryName"]=> array(0) { } ["Phone"]=> array(0) { } ["PostalCode"]=> array(0) { } ["ExternalAddressID"]=> array(0) { } } ["ShippingServiceSelected"]=> array(2) { ["ShippingService"]=> string(12) "ePacketChina" ["ShippingServiceCost"]=> string(3) "7.0" } ["Subtotal"]=> string(5) "19.99" ["Total"]=> string(5) "26.99" ["TransactionArray"]=> array(1) {

//   ["Transaction"]=> array(13) {
//    ["Buyer"]=> array(3) { ["Email"]=> string(20) "johnchya12@gmail.com" ["UserFirstName"]=> array(0) { } ["UserLastName"]=> array(0) { } } ["ShippingDetails"]=> array(1) { ["SellingManagerSalesRecordNumber"]=> string(3) "726" } ["CreatedDate"]=> string(24) "2017-06-03T00:39:21.000Z" ["Item"]=> array(6) { ["ApplicationData"]=> string(28) "ic6d9i84269458088131393931a6" ["ItemID"]=> string(12) "322418069097" ["Site"]=> string(2) "US" ["Title"]=> string(81) "Undertale Sans Cosplay Costume Blue Hoodie Hooded Winter Coat Sweater Jacket [XL]" ["ConditionID"]=> string(4) "1000" ["ConditionDisplayName"]=> string(13) "New with tags" } ["QuantityPurchased"]=> string(1) "1" ["Status"]=> array(1) { ["PaymentHoldStatus"]=> string(4) "None" } ["TransactionID"]=> string(13) "1760760719011" ["TransactionPrice"]=> string(5) "19.99" ["TransactionSiteID"]=> string(2) "US" ["Platform"]=> string(4) "eBay" 


//    ["Variation"]=> array(4) {
//     ["SKU"]=> string(9) "131563-XL" ["VariationSpecifics"]=> array(1) { ["NameValueList"]=> array(2) { ["Name"]=> string(4) "Size" ["Value"]=> string(2) "XL" } } ["VariationTitle"]=> string(81) "Undertale Sans Cosplay Costume Blue Hoodie Hooded Winter Coat Sweater Jacket [XL]" ["VariationViewItemURL"]=> string(77) "http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&item=322418069097&vti=Size%09XL" 
// } 


// ["Taxes"]=> array(2) { ["TotalTaxAmount"]=> string(3) "0.0" ["TaxDetails"]=> array(2) { [0]=> array(6) { ["Imposition"]=> string(8) "SalesTax" ["TaxDescription"]=> string(8) "SalesTax" ["TaxAmount"]=> string(3) "0.0" ["TaxOnSubtotalAmount"]=> string(3) "0.0" ["TaxOnShippingAmount"]=> string(3) "0.0" ["TaxOnHandlingAmount"]=> string(3) "0.0" } [1]=> array(3) { ["Imposition"]=> string(17) "WasteRecyclingFee" ["TaxDescription"]=> string(27) "ElectronicWasteRecyclingFee" ["TaxAmount"]=> string(3) "0.0" } } } ["OrderLineItemID"]=> string(26) "322418069097-1760760719011" 
// } }



//   ["BuyerUserID"]=> string(12) "johnchya12-6" ["IntegratedMerchantCreditCardEnabled"]=> string(5) "false" ["EIASToken"]=> string(56) "nY+sHZ2PrBmdj6wVnY+sEZ2PrA2dj6ACk4OpCpKHpg6dj6x9nY+seQ==" }


//检查sku是否存在于服务器中，如果不存在，则判定为待处理单
public function checksku(){
	$this->amazondata=new amazondata();
	$row = $this->db1->get_where("db_ebayorder","is_updata=0")->result_array();

if (empty($row)) {
	//说明无新单子导入
	echo "无订单！";
	exit;
}else{
	//说明有新单子导入
	foreach ($row as $v) {
	//核对sku
	if (empty($v['PaidTime'])) {

		  $sql="delete from db_ebayorder where e_id = ".$v['e_id'];
		  $this->db1->query($sql);
		continue;
	}
	if ($v['OrderStatus']=='Cancelled') {
	$this->db1->update("db_ebayorder",array("is_updata"=>'1'),"e_id=".$v['e_id']);
	continue;
	}
	// $contime=time()-15*3600*24;
 //    if (strtotime($v['CreatedTime'])<$contime) {
	// $this->db1->update("db_ebayorder",array("is_updata"=>'1'),"e_id=".$v['e_id']);
	// continue;
	// }
	
	$TransactionArray = json_decode($v['TransactionArray'],true);
	$ShippingDetails = json_decode($v['ShippingDetails'],true);
	$MonetaryDetails=json_decode($v['MonetaryDetails'],true);
	$transat=$TransactionArray['Transaction'];


	$TransactionID=(isset($transat['TransactionID'])?$transat['TransactionID']:$transat[0]['TransactionID']);
	if(!isset($transat['TransactionID']))
{
unset($transat);
$transat=$TransactionArray['Transaction'][0];

}

$skuarr=array();

if (isset($TransactionArray['Transaction'][0])) {
	$skui=count($TransactionArray['Transaction']);
	for ($i=0; $i <$skui ; $i++) {
		$skuarr[]= isset($TransactionArray['Transaction'][$i]['Variation']['SKU'])?$TransactionArray['Transaction'][$i]['Variation']['SKU']:$TransactionArray['Transaction'][$i]['Item']['SKU'];
	}
}else{
	 $skuarr[]= isset($TransactionArray['Transaction']['Variation']['SKU'])?$TransactionArray['Transaction']['Variation']['SKU']:$TransactionArray['Transaction']['Item']['SKU'];
}


  foreach ($skuarr as $key=>$sku) {
	  $sku = addslashes(trim($sku));
      $check=$this->db1->get_where("db_goods","goods_sku='{$sku}'")->result_array();      
if (empty($check)) {
	$checklist=$this->db1->get_where("db_goods","cognatelist like '%,{$sku},%'")->result_array();
    if(empty($checklist)){
    	$Status=7;
    	break;
    }else{

$skuarr[$key]=$checklist[0]['goods_sku'];

    	$Status=2;
    }
}else{
    $Status=2;
}
    }  
 

$shopid=$v['shopid'];

$ShippingAddress=json_decode($v['ShippingAddress'],true);


//查询订单是否已被导入
			$rorder = $this->db1->get_where("db_order_list","tradeid='".$ShippingDetails['SellingManagerSalesRecordNumber']."' AND shopid='".$shopid."'")->result_array();
			
			if(count($rorder)==1)
			{
				$this->db1->update("db_ebayorder",array("is_updata"=>'1'),"e_id=".$v['e_id']);
				continue;
			}
			$rorder1 = $this->db1->get_where("db_order_list","ebay_orderID='".$v['OrderID']."' AND shopid='".$shopid."'")->result_array();
			
			if(count($rorder1)==1)
			{
				$this->db1->update("db_ebayorder",array("is_updata"=>'1'),"e_id=".$v['e_id']);
				continue;
			}
           //获取信息准备导入。
			 
			if(empty($ShippingAddress['Name']) && empty($ShippingAddress['CountryName']) && empty($ShippingAddress['Phone']) &&  empty($ShippingAddress['Street1']) &&  empty($ShippingAddress['Street2']) &&  empty($ShippingAddress['PostalCode']))
			{
				continue;
			}
	
            $postdata="";
			$postdata["order_sn"] = $this->amazondata->getNo('ebay',$TransactionID,$shopid);
			$postdata["ebay_orderID"] =$v['OrderID'];
			$postdata["dates"] = date("Y-m-d");
			$postdata["order_status"] = $Status;
			$postdata["order_source"] ='正常订单';
			$postdata['shipping_status']=0;
			$postdata["customerid"] =addslashes(trim($v['BuyerUserID']));
			
			$postdata["consignee"] =addslashes(trim($ShippingAddress['Name']));

			if($ShippingAddress['CountryName']=='Österreich')
			{
				$ShippingAddress['CountryName'] = 'Austria';
			}
			$postdata["country"] = $ShippingAddress['CountryName'];
			$postdata["country_code"]= $ShippingAddress['Country'];
			
			
//				$rscountry = $this->db1->get_where("d_chinaexpress","NAME='".$ShippingAddress['CountryName']."'")->result_array();
//				if(isset($rscountry[0]["id"])){
//					$postdata["country_cn"] = $rscountry[0]["FILED1"];
//				}else{
//					$postdata["country_cn"]='';
//				}
			if($ShippingAddress['CountryName']){
				$rscountry = $this->db1->get_where("d_country","countrynamecn='".$ShippingAddress['CountryName']."'or countryid = '".$ShippingAddress['CountryName']."' or countrynamede ='".$ShippingAddress['CountryName']."'")->result_array();
				if(isset($rscountry[0]["id"])){
					$postdata["country_cn"] = $rscountry[0]["countrynameen"];
				}else{
					$rscountry = $this->db1->get_where("d_chinaexpress","NAME='".$ShippingAddress['CountryName']."'")->result_array();
					if(isset($rscountry[0]["id"])){
						$postdata["country_cn"] = $rscountry[0]["FILED1"];
						}else{
							$postdata["country_cn"]='';
						}
				}
			}

			$phone = gettype($ShippingAddress['Phone'])=='string'?$ShippingAddress['Phone']:'';
			if($phone=='Invalid Request')
			{
				$phone = "";
			}
			$postdata["province"] = gettype($ShippingAddress['StateOrProvince'])=='string'?$ShippingAddress['StateOrProvince']:'';
			$postdata["city"] = gettype($ShippingAddress['CityName'])=='string'?$ShippingAddress['CityName']:'';
			$postdata["address"] = addslashes(trim(gettype($ShippingAddress['Street1'])=='string'?$ShippingAddress['Street1']:''));
			$postdata["address2"] = addslashes(trim(gettype($ShippingAddress['Street2'])=='string'?$ShippingAddress['Street2']:''));
			$postdata["zipcode"] = gettype($ShippingAddress['PostalCode'])=='string'?$ShippingAddress['PostalCode']:'';
			$postdata["tel"] = $phone;
			$postdata["mobile"] ='';
			$postdata["email"] = isset($transat['Buyer']['Email'])=='string'?$transat['Buyer']['Email']:'';
			$postdata["shopid"] = $shopid;
			$rshop = $this->db1->get_where("d_shop","id=".$shopid)->result_array();
			$postdata["shopname"] = $rshop[0]["name"];
			$postdata["shopoper"] = $rshop[0]["updateoper"];
			
			$postdata["moneytype"] =$v['currencyID'];
			$exchange=$this->db1->get_where("d_moneyrate","name='{$v['currencyID']}'")->result_array();
			$exchangerate=$exchange[0]["rate"];
			//$postdata["tradeid"] = $TransactionID;
			$postdata["tradeid"] = $ShippingDetails['SellingManagerSalesRecordNumber']?$ShippingDetails['SellingManagerSalesRecordNumber']:$TransactionID;
			
			if(count($ShippingDetails) ==count($ShippingDetails, 1))
			{
				$ShippingService = $ShippingDetails["ShippingService"];
			}else{
				if(isset($ShippingDetails['ShippingServiceOptions'][0])){
					$ShippingService = $ShippingDetails['ShippingServiceOptions'][0]['ShippingService'];
				}else{
					$ShippingService = $ShippingDetails['ShippingServiceOptions']['ShippingService'];
				}
				
			}
			$postdata["postageservice"] = $ShippingService?$ShippingService:NULL;
			$postdata['shipping_id']='';
			$postdata['shipping_name']='';
			$postdata['shipping_time']='';
			$postdata["goods_originask"] =$v['Subtotal'];//订单原始金额
			$postdata["goods_amount"] =$v['Subtotal']*$exchangerate;//订单rmb
		    $ShippingServiceSelectedarr = json_decode($v['ShippingServiceSelected'],true);
			$postdata["shipping_fee"] = $ShippingServiceSelectedarr['ShippingServiceCost']*$exchangerate;//运费rmb
			$postdata["shipping_originask"] = $ShippingServiceSelectedarr['ShippingServiceCost'];//运费原始金额
			$postdata["add_time"] = time();
			$postdata["ordertime"] = date("Y-m-d H:i:s",strtotime($transat['CreatedDate']));
			$postdata["saleschannel"] = 'eBay';
			$postdata["pay_fee"] = $MonetaryDetails['Payments']['Payment']['FeeOrCreditAmount']*$exchangerate;
			$postdata['pack_fee']='';
			$postdata["platform_fee"] = $v['Subtotal']*0.15*$exchangerate;
			$postdata["surplus"]="";
			$postdata["paypalmail"]=isset($transat['Buyer']['Email'])?$transat['Buyer']['Email']:'';
			$postdata["platform_message"]=$v['BuyerCheckoutMessage'];
		    $postdata["payid"]=$MonetaryDetails['Payments']['Payment']['ReferenceID'];
		    $postdata["payaccount"]=$v['SellerEmail'];
			$postdata['platformID']  = $rshop[0]['platfrom'];//平台
			$postdata['moneyrate']  = $exchangerate;//汇率

			
		    //return $postdata;

		   
			$this->db1->trans_begin();
			try{
				$this->db1->insert("db_order_list",$postdata);
				$orderID = $this->db1->insert_id();
				$this->db1->update("db_ebayorder",array("is_updata"=>'1'),"e_id=".$v['e_id']);
				
				$factorycode =$this->amazondata->factorycode();
				$weight = 0;
				// foreach($sell as $key=>$res)
				// {
				$itemidi=0;
					foreach ($skuarr as $key =>$sku) {
						$sku = addslashes(trim($sku));
					$rgoods = $this->db1->get_where("db_goods","goods_sku='".$sku."'")->result_array();
					$QuantityPurchased=isset($TransactionArray['Transaction'][$itemidi]['QuantityPurchased'])?$TransactionArray['Transaction'][$itemidi]['QuantityPurchased']:$TransactionArray['Transaction']['QuantityPurchased'];
					$TransactionPrice=isset($TransactionArray['Transaction'][$itemidi]['TransactionPrice'])?$TransactionArray['Transaction'][$itemidi]['TransactionPrice']:$TransactionArray['Transaction']['TransactionPrice'];
					if(isset($rgoods[0]["goods_id"]))
					{
						$goods_id = $rgoods[0]["goods_id"];
						$g_weight = $rgoods[0]["g_weight"]?$rgoods[0]["g_weight"]:400;
						$sweight = $g_weight;
						$weight = $weight+$sweight;
						/*****************成本价计算方式********
						**  11、12开头定制的衣服按成本价计算
						**  批量的sku 按关联价计算
						**  外采购的衣服按成本价计算
						*********************************/
						if(is_numeric($sku) && preg_match('|^\d{8}$|',$sku))	//数字并且8位SKU并且11 12开头
						{
							$goodscode  = substr($sku,0,2);//取开头2位数
							if(in_array($goodscode,$factorycode))	//是否存在在工厂code
							{
								$costprice = $rgoods[0]["g_costprice"];	//定制衣服按成本价计算
							}
						}else{
							//如果当前SKU不是8位，查询父SKU是不是8位并且11，12开头
							if(is_numeric($rgoods[0]["goods_parent_sku"]) && preg_match('|^\d{8}$|',$rgoods[0]["goods_parent_sku"]))	//数字并且8位SKU并且11 12开头
							{
								$goodscodes  = substr($rgoods[0]["goods_parent_sku"],0,2);//取开头2位数
								if(in_array($goodscodes,$factorycode))	//是否存在在工厂code
								{
									$costprice = $rgoods[0]["bulkprice"];	//批量按关联价计算
								}
							}else{
								$costprice = $rgoods[0]["g_costprice"];
							}
						}
						



					}else{
						$goods_id = 0 ;
						$sweight=400;
					}
					$postsell = "";
					$postsell["order_id"] = $orderID;
					$postsell["goods_id"] = $goods_id;
					$postsell["goods_name"] = addslashes(isset($TransactionArray['Transaction'][$itemidi]['Item']['Title'])?$TransactionArray['Transaction'][$itemidi]['Item']['Title']:$TransactionArray['Transaction']['Item']['Title']);
					$postsell["goods_sn"] =  $sku;
					$postsell["costprice"] =isset($costprice)?$costprice:'';
					$postsell["goods_number"] = $QuantityPurchased;
					$postsell["goods_price"] = $TransactionPrice*$exchangerate;
					$postsell["goods_weight"]=$sweight;
					$postsell["goods_amount"] = $QuantityPurchased* $TransactionPrice*$exchangerate;
					$postsell["originsellprice"] = isset($TransactionArray['Transaction'][$itemidi]['TransactionPrice'])?$TransactionArray['Transaction'][$itemidi]['TransactionPrice']:$TransactionArray['Transaction']['TransactionPrice'];
					$postsell["originsku"] = $sku;
					$postsell["product_link"]=isset($TransactionArray['Transaction'][$itemidi]['Item']['ItemID'])?$TransactionArray['Transaction'][$itemidi]['Item']['ItemID']:$TransactionArray['Transaction']['Item']['ItemID'];
		    unset($sale_remark);
		    $sale_remark='';
		    if(isset($TransactionArray['Transaction'][$itemidi]['Variation']['VariationSpecifics'])){
		    	$vvn =$TransactionArray['Transaction'][$itemidi]['Variation']['VariationSpecifics'];
		    	if (isset($TransactionArray['Transaction'][$itemidi]['Variation']['VariationSpecifics']['NameValueList'][0])) {
		    		$vvn =$TransactionArray['Transaction'][$itemidi]['Variation']['VariationSpecifics']['NameValueList'];
		    	}		    	
		    	foreach ($vvn as $value) {
	$sale_remark.=$value['Name'].'&nbsp'.$value['Value'].'&nbsp';
}
		    }



					$postsell["sale_remark"]=$sale_remark;
					$this->db1->insert("db_order_sell",$postsell);

					if($goods_id==0)
					{
						$this->db1->update("db_order_list",array("order_status"=>7),"order_id=".$orderID);
					}
					if($weight)
					{
						$this->db1->update("db_order_list",array("orderweight"=>$weight),"order_id=".$orderID);
					}
					$itemidi++;
				 }
                //更新日志
				$imgdata["goods_id"] = $orderID;	//订单ID
				$imgdata["updatetime"] = date("Y-m-d H:i:s");
				$imgdata["createUid"] = 0;
				$imgdata["types"] = 3;
				$imgdata["content"] = 'ebay接口自动新增订单,交易ID='.$TransactionID;
				$imgdata["createUser"] ='auto';
				$this->db1->query($this->db1->insert_string('db_goods_log', $imgdata));
				

				$this->db1->trans_commit();
			}catch (Exception $e){
				$this->db1->trans_rollback();
				$msg =  $e->getMessage();
				print_r($msg);exit;
			}










  }
}


}



	

}